<?php
declare(strict_types=1);

namespace Service\PayService;

use Service\BaseService;
use Service\Code\Normal;

/**
 * 小程序支付中心
 * @author chenshubo
 */
class MnappPayService extends BaseService
{
    public $pay_way = 
    [
        0 => 'wxmnapp',//微信小程序支付
        1 => 'hnapay',//新生支付
        2 => 'allinpay',//通联支付
    ];
    
    /**
     * mnid = 4 c端小程序
     * mnid = 2 大b小程序
     * 收银机支付功能
     * @param int $cid
     * @param int $mn_sid
     * @param array $extra
     */
    public function userPay(int $cid,int $mn_sid,int $mnid,int $pay_way,array $extra)
    {
        if( empty($this->pay_way[$pay_way]) ) {
            return Normal::returnCode(Normal::FAIL, "当前支付方式pay_way[{$pay_way}]不存在");
        }
        
        if( empty($extra['order_no']) ) {
            return Normal::returnCode(Normal::FAIL, "支付订单参数order_no不能为空");
        }
        
        if( empty($extra['order_id']) ) {
            return Normal::returnCode(Normal::FAIL, "支付订单参数order_id不能为空");
        }
        
        if( empty($extra['money']) ) {
            return Normal::returnCode(Normal::FAIL, "支付订单参数money不能为空");
        }
        
        $payer      = ucfirst($this->pay_way[$pay_way]);
        $className  = "Service\PayService\Payer\\{$payer}";
        $callMethod = 'userPay';
        if (!class_exists($className)) {
            return Normal::returnCode(Normal::FAIL, "服务类【{$className}】不存在");
        }
        if (!method_exists($className, $callMethod)) {
            return Normal::returnCode(Normal::FAIL, "服务类【{$className}】方法【{$callMethod}】不存在");
        }
        
        try {
            $result = $className::instance()->{$callMethod}($cid,$mn_sid,$mnid,$extra);
            if( $result['code'] == Normal::SUC ) {
                $result['data']['payWay'] = $pay_way;
                $result['data']['payWayName'] = $payer;
            }
            return $result;
        } catch ( \Throwable $th ) {
            return Normal::returnCode(Normal::FAIL, "支付服务中心异常[{$th->getMessage()},{$th->getFile()},{$th->getLine()}]");
        }
    }
}